package com.qian.saas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qian.saas.domain.Users;
import com.qian.saas.mapper.UsersMapper;
import io.jsonwebtoken.*;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class Loginuser {

    @Resource
    private UsersMapper usersMapper;

    /**
     * 获取用户信息
     * @param token
     * @return
     */
    @GetMapping("/info")
    public R getInfo(String token) {
        R resStr;
        System.out.println(token);
        JwtParser jwtParser = Jwts.parser(); //获取jwt解析器
        jwtParser.setSigningKey("qianfeng");
        try {
            //如果token正确(密码，有效期)则正常运行，否则抛出异常
            Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
            Claims body = claimsJws.getBody();//获取body
            String subject = body.getSubject();//获取body中subject中的值
            String key = body.get("kay", String.class);//获取Claims中map的值
            Users tonuser = JSON.parseObject(key, Users.class);//反序列化user
            JSONObject jsonObject = new JSONObject();
            ArrayList<String> roleList = new ArrayList<>();
            roleList.add(tonuser.getType());
            jsonObject.put("roles",roleList); //角色
            jsonObject.put("introduction","这是介绍"); //介绍
            jsonObject.put("name",tonuser.getUsername()); //name
            jsonObject.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif"); //头像
            resStr = R.success(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("token失效");
        }
        return resStr;
    }

    /**
     * 等出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public String logout(HttpServletRequest request) {
        Map r = new HashMap();
        r.put("code", 20000);
        r.put("message", "登出成功");
        return JSON.toJSONString(r);
    }

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping(value = "/doLogin")
    public R doLogin(@RequestBody Users user) {
        R resStr;
        try {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("username", user.getUsername());
            wrapper.eq("password",user.getPassword());
            Users users = usersMapper.selectOne(wrapper);
            if (users == null) return R.error("账号或密码不正确");
            String userJson = JSON.toJSONString(users);//序列化user
            JwtBuilder jwtBuilder = Jwts.builder(); //获得JWT构造器
            Map<String, Object> map = new Hashtable<>();
            map.put("kay", userJson);
            String token = jwtBuilder.setSubject("hello") //设置用户数据
                    .setIssuedAt(new Date()) //设置jwt生成时间
                    .setId(users.getId().toString()) //设置id为token id
                    .setClaims(map) //通过map传值
                    .setExpiration(new Date(System.currentTimeMillis() + 50000)) //设置token有效期
                    .signWith(SignatureAlgorithm.HS256, "qianfeng") //设置token加密方式和密码
                    .compact(); //生成token字符串

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("token", token); //token在此先暂时随便定义
            resStr = R.success(jsonObject);
        } catch (Exception e) {
            resStr = R.error("失败：" + e.getMessage());
            e.printStackTrace();
        }
        return resStr;
    }

    @PostMapping("/logon")
    public R logon(@RequestBody Users users){
        System.out.println(users);
        users.setType("普通");
        usersMapper.insert(users);
        return R.success("f");
    }
}
